// ==UserScript==
// @name         学习平台视频自动观看助手
// @namespace    http://tampermonkey.net/
// @version      1.2
// @description  保持视频播放活跃状态，模拟鼠标移动和防止计时暂停
// @author       You
// @match        *://xuexi.jsou.cn/*
// @match        *://service-cdn.qiqiuyun.net/*
// @grant        none
// ==/UserScript==

(function() {
    'use strict';

    // Log when the script starts
    console.log('Video Player Mouse Movement script activated');

    // Function to remove mouseout event listeners
    function removeMouseOutListeners() {
        // Find all potential video player elements
        const potentialPlayers = document.querySelectorAll('video, div[class*="player"], div[class*="video"], iframe[src*="youtube"], iframe[src*="vimeo"]');

        potentialPlayers.forEach(element => {
            // Option 1: Try to use the non-standard getEventListeners if available (works in Chrome DevTools)
            if (window.getEventListeners) {
                try {
                    const listeners = window.getEventListeners(element);
                    if (listeners && listeners.mouseout) {
                        listeners.mouseout.forEach(listener => {
                            element.removeEventListener('mouseout', listener.listener);
                            console.log('Removed mouseout listener from element', element);
                        });
                    }
                } catch (e) {
                    // Ignore errors, getEventListeners is not standard
                }
            }

            // Option 2: Override the element's onmouseout property
            element.onmouseout = null;

            // Option 3: Clone the node to remove all event listeners
            try {
                const parent = element.parentNode;
                if (parent) {
                    const clone = element.cloneNode(true);
                    parent.replaceChild(clone, element);
                    console.log('Replaced element to remove all listeners', clone);
                }
            } catch (e) {
                console.log('Error cloning element:', e);
            }
        });

        // Override document mouseout
        document.onmouseout = null;

        console.log('Attempted to remove mouseout listeners from video elements');
    }

    // Run the function immediately
    removeMouseOutListeners();

    // Also run it periodically to catch new elements
    setInterval(removeMouseOutListeners, 300000); // Every 5 minutes

    // Function to check if videos are playing and start playback if needed
    function checkAndPlayVideos() {
        // Find all video elements
        const videoElements = document.querySelectorAll('video');

        videoElements.forEach(video => {
            // Check if video is paused or ended
            if (video.paused || video.ended) {
                try {
                    // Try to play the video
                    const playPromise = video.play();

                    // Handle the promise to avoid uncaught promise errors
                    if (playPromise !== undefined) {
                        playPromise.then(() => {
                            console.log('Successfully started playback for video:', video);
                        }).catch(error => {
                            console.log('Auto-play was prevented:', error);

                            // Try to find and click play buttons
                            const parentElement = video.closest('div[class*="player"], div[class*="video"]');
                            if (parentElement) {
                                // Look for play buttons with common selectors
                                const playButtons = parentElement.querySelectorAll('button[class*="play"], .play-button, .vjs-play-control, .ytp-play-button, [aria-label*="Play"], [title*="Play"]');

                                if (playButtons.length > 0) {
                                    // Click the first play button found
                                    playButtons[0].click();
                                    console.log('Clicked play button');
                                }
                            }
                        });
                    }
                } catch (e) {
                    console.log('Error attempting to play video:', e);
                }
            }
        });

        // Also check for common video player containers and try to click play buttons
        const playerContainers = document.querySelectorAll('div[class*="player"], div[class*="video"], .bilibili-player-video-btn-start, .prism-player');

        playerContainers.forEach(container => {
            // Look for visible play buttons
            const playButtons = container.querySelectorAll('button[class*="play"], .play-button, .vjs-play-control, .ytp-play-button, [aria-label*="Play"], [title*="Play"]');

            // Check if the container or any of its ancestors has a class that indicates it's paused
            const isPaused = container.classList.contains('paused') ||
                           container.classList.contains('vjs-paused') ||
                           container.classList.contains('is-paused') ||
                           !!container.querySelector('.paused, .vjs-paused, .is-paused');

            if (isPaused && playButtons.length > 0) {
                // Click the first play button found
                playButtons[0].click();
                console.log('Clicked play button on paused player:', container);
            }
        });

        console.log('Checked video playback status');
    }

    // Run the video check immediately
    checkAndPlayVideos();

    // Also run it periodically
    setInterval(checkAndPlayVideos, 60000); // Every minute

    // Function to find video player elements
    function findVideoPlayers() {
        // Common video player selectors
        const playerSelectors = [
            'video',                  // HTML5 video elements
            '.video-player',          // Common class for video players
            '.player-container',      // Another common class
            '.plyr',                  // Plyr player
            '.vjs-tech',              // VideoJS
            '.html5-video-player',    // YouTube
            'iframe[src*="youtube"]', // YouTube iframes
            'iframe[src*="vimeo"]',   // Vimeo iframes
            '.bilibili-player-video', // Bilibili player
            '.prism-player'           // Aliyun player
        ];

        // Try to find elements matching any of the selectors
        for (const selector of playerSelectors) {
            const elements = document.querySelectorAll(selector);
            if (elements && elements.length > 0) {
                return Array.from(elements);
            }
        }

        // Fallback: look for large media containers
        const possibleContainers = document.querySelectorAll('div[class*="player"], div[class*="video"], div[id*="player"], div[id*="video"]');
        if (possibleContainers && possibleContainers.length > 0) {
            return Array.from(possibleContainers);
        }

        // Return an empty array if no elements found
        return [];
    }

    // Function to simulate mouse movement within a video player
    function simulateMouseMovement() {
        const players = findVideoPlayers();

        if (players.length === 0) {
            // No players found, move mouse within window
            const randomX = Math.floor(Math.random() * window.innerWidth);
            const randomY = Math.floor(Math.random() * window.innerHeight);

            const moveEvent = new MouseEvent('mousemove', {
                view: window,
                bubbles: true,
                cancelable: true,
                clientX: randomX,
                clientY: randomY
            });

            document.dispatchEvent(moveEvent);
            console.log(`No video players found. Mouse moved to position (${randomX}, ${randomY}) at ${new Date().toLocaleTimeString()}`);
            return;
        }

        // Select a random player from the array
        const player = players[Math.floor(Math.random() * players.length)];

        // Get the player's position and dimensions
        const rect = player.getBoundingClientRect();

        // Generate random coordinates within the player
        const randomX = Math.floor(rect.left + Math.random() * rect.width);
        const randomY = Math.floor(rect.top + Math.random() * rect.height);

        // Create and dispatch mousemove event
        const moveEvent = new MouseEvent('mousemove', {
            view: window,
            bubbles: true,
            cancelable: true,
            clientX: randomX,
            clientY: randomY
        });

        // Dispatch to the player element
        player.dispatchEvent(moveEvent);

        console.log(`Mouse moved within video player to position (${randomX}, ${randomY}) at ${new Date().toLocaleTimeString()}`);
    }

    // 针对xuexi.jsou.cn学习平台的特定功能
    function jsouSpecificActions() {
        // 检查是否在学习平台页面
        if (window.location.hostname.includes('jsou.cn')) {
            // 1. 处理iframe视频播放器
            const videoFrames = document.querySelectorAll('iframe[src*="service-cdn.qiqiuyun.net"]');
            if (videoFrames.length > 0) {
                console.log('找到视频iframe播放器:', videoFrames.length);
                
                // 尝试保持iframe内视频焦点活跃
                videoFrames.forEach(frame => {
                    // 模拟鼠标在iframe上移动
                    const frameRect = frame.getBoundingClientRect();
                    const centerX = Math.floor(frameRect.left + frameRect.width/2);
                    const centerY = Math.floor(frameRect.top + frameRect.height/2);
                    
                    const moveEvent = new MouseEvent('mousemove', {
                        view: window,
                        bubbles: true,
                        cancelable: true,
                        clientX: centerX,
                        clientY: centerY
                    });
                    
                    frame.dispatchEvent(moveEvent);
                    
                    // 尝试聚焦iframe
                    try {
                        frame.contentWindow.focus();
                    } catch(e) {
                        // 可能因为跨域限制无法访问iframe内容
                    }
                });
            }
            
            // 2. 检查计时元素，确保视频计时正常运行
            const timeCounter = document.getElementById('stuResourceViewTime');
            if (timeCounter) {
                console.log('找到学习时间计数器，当前显示:', timeCounter.textContent);
                
                // 保存上次检查的时间值
                if (!window._lastTimeValue) {
                    window._lastTimeValue = timeCounter.textContent;
                    window._stuckCounter = 0;
                } else if (window._lastTimeValue === timeCounter.textContent) {
                    // 如果计时器停止，增加停止计数
                    window._stuckCounter++;
                    console.log(`计时器似乎停止了 ${window._stuckCounter} 次检查`);
                    
                    // 如果连续多次检测到计时器停止，尝试修复
                    if (window._stuckCounter >= 3) {
                        console.log('尝试重新激活计时器...');
                        
                        // 模拟在页面上的活跃度
                        document.body.click();
                        
                        // 重置计数器
                        window._stuckCounter = 0;
                    }
                } else {
                    // 计时器在正常更新，重置停止计数
                    window._lastTimeValue = timeCounter.textContent;
                    window._stuckCounter = 0;
                }
            }
            
            // 3. 防止页面检测到不活跃
            // 模拟每隔一段时间的页面交互，防止系统检测不活跃
            const randomActivity = () => {
                const events = ['mousemove', 'mousedown', 'mouseup', 'keydown', 'keyup'];
                const randomEvent = events[Math.floor(Math.random() * events.length)];
                
                // 创建并分发随机事件
                let event;
                
                if (randomEvent.startsWith('mouse')) {
                    const x = Math.floor(Math.random() * window.innerWidth);
                    const y = Math.floor(Math.random() * window.innerHeight);
                    
                    event = new MouseEvent(randomEvent, {
                        view: window,
                        bubbles: true,
                        cancelable: true,
                        clientX: x,
                        clientY: y
                    });
                } else {
                    // 键盘事件
                    event = new KeyboardEvent(randomEvent, {
                        bubbles: true,
                        cancelable: true,
                        keyCode: 32 // 空格键
                    });
                }
                
                document.dispatchEvent(event);
                console.log(`触发随机活动事件: ${randomEvent}`);
            };
            
            // 每分钟随机触发一个活动事件
            if (!window._randomActivityInterval) {
                window._randomActivityInterval = setInterval(randomActivity, 60000);
            }
        }
        
        // 如果在iframe中（视频播放器iframe内）
        if (window.location.hostname.includes('qiqiuyun.net')) {
            console.log('在视频播放器iframe内运行脚本');
            
            // 尝试与SDK交互，保持视频播放
            if (window.sdk) {
                console.log('找到视频SDK对象');
                
                // 确保视频在播放
                try {
                    // 检查是否暂停
                    if (window.sdk.isPaused && window.sdk.isPaused()) {
                        console.log('检测到视频暂停，尝试播放...');
                        window.sdk.play();
                    }
                    
                    // 监听暂停事件，自动恢复播放
                    if (!window._pauseListenerAdded) {
                        window.sdk.on('paused', function() {
                            console.log('视频被暂停，1秒后自动恢复...');
                            setTimeout(() => window.sdk.play(), 1000);
                        });
                        window._pauseListenerAdded = true;
                    }
                } catch(e) {
                    console.log('与SDK交互失败:', e);
                }
            }
        }
    }
    
    // 每5秒运行一次特定平台功能
    setInterval(jsouSpecificActions, 5000);
    
    // 立即运行一次
    jsouSpecificActions();
    
    // Set interval to simulate movement every 10 minutes (600000 ms)
    const intervalId = setInterval(simulateMouseMovement, 600000);
    
    // Run once immediately on script load
    simulateMouseMovement();
    
    // Add a way to stop the simulation if needed
    window.stopAutoMouseMovement = function() {
        clearInterval(intervalId);
        if (window._randomActivityInterval) {
            clearInterval(window._randomActivityInterval);
            window._randomActivityInterval = null;
        }
        console.log('Video Player Mouse Movement stopped');
    };
})();